<template>
  <view class="page-container">
    <view class="bg">
      <view class="image-wrapper">
        <image
          v-if="!isPlayingAnimation"
          class="bg-image default-image"
          :src="defaultImage"
          mode="aspectFit"
          :style="{ width: '100%', height: '100%' }"
          @load="onImageLoad"
        />
        <image
          v-if="isPlayingAnimation"
          class="bg-image animation-image"
          :src="currentImage"
          mode="aspectFit"
          :style="{ width: '100%', height: '100%' }"
          @load="onImageLoad"
        />
        <image
          v-if="nextImage"
          class="bg-image preload-image"
          :src="nextImage"
          mode="aspectFit"
          :style="{ width: '100%', height: '100%' }"
        />
      </view>
    </view>

    <view class="controls-container">
      <view class="left-controls">
        <button class="action-btn" @click="playAnimation('drink', 80, 50)">喝水</button>
        <button class="action-btn" @click="playAnimation('eat', 39, 50)">吃饭</button>
        <button class="action-btn" @click="playCymbal">打鼓</button>
        <button class="action-btn" @click="playFart">放屁</button>
      </view>

      <view class="right-controls">
        <button class="action-btn" @click="playAnimation('pie', 23, 100)">砸饼</button>
        <button class="action-btn" @click="playAnimation('scratch', 55, 100)">抓屏幕</button>
        <button class="action-btn" @click="playAnimation('footLeft', 29, 100)">左脚</button>
        <button class="action-btn" @click="playAnimation('footRight', 29, 100)">右脚</button>
        <button class="action-btn" @click="playStomach">肚子</button>
        <button class="action-btn" @click="playAnimation('knockout', 80, 100)">晕倒</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const props = defineProps<{
  disableAnimation?: boolean
}>()

const defaultImage = '/static/assets/img/Animations/angry/angry_00.jpg'
const currentImage = ref(defaultImage)
const nextImage = ref('')
let animationTimer: number | null = null
const preloadedImages = new Set<string>()
const isPlayingAnimation = ref(false)
const imageLoaded = ref(false)

// 图片加载完成处理
const onImageLoad = () => {
  imageLoaded.value = true
}

// 预加载图片
const preloadImage = (src: string) => {
  if (preloadedImages.has(src)) return
  return new Promise<void>((resolve, reject) => {
    uni.getImageInfo({
      src: src,
      success: () => {
        preloadedImages.add(src)
        resolve()
      },
      fail: (err) => {
        console.error('预加载图片失败:', err)
        reject(err)
      },
    })
  })
}

// 预加载所有动画序列
const preloadAllAnimations = async () => {
  const animations = [
    { path: 'drink', total: 80 },
    { path: 'eat', total: 39 },
    { path: 'cymbal', total: 12 },
    { path: 'fart', total: 27 },
    { path: 'pie', total: 23 },
    { path: 'scratch', total: 55 },
    { path: 'footLeft', total: 29 },
    { path: 'footRight', total: 29 },
    { path: 'stomach', total: 33 },
    { path: 'knockout', total: 80 },
  ]

  try {
    // 预加载默认图片
    await preloadImage(defaultImage)

    // 预加载所有动画序列
    const preloadPromises = animations.map(({ path, total }) => {
      const promises = []
      for (let i = 1; i <= total; i++) {
        const num = i < 10 ? `0${i}` : `${i}`
        const src = `/static/assets/img/Animations/${path}/${path}_${num}.jpg`
        promises.push(preloadImage(src))
      }
      return Promise.all(promises)
    })

    await Promise.all(preloadPromises)
    console.log('所有图片预加载完成')
  } catch (error) {
    console.error('预加载图片失败:', error)
  }
}

const playAnimation = async (path: string, total: number, timing: number) => {
  if (animationTimer) {
    clearInterval(animationTimer)
    animationTimer = null
  }

  isPlayingAnimation.value = true
  imageLoaded.value = false
  let num1 = 0

  // 预加载下一帧
  const preloadNextFrame = async (nextNum: number) => {
    if (nextNum <= total) {
      const num = nextNum < 10 ? `0${nextNum}` : `${nextNum}`
      const src = `/static/assets/img/Animations/${path}/${path}_${num}.jpg`
      nextImage.value = src
      await preloadImage(src)
    }
  }

  const play = async () => {
    num1++
    const num = num1 < 10 ? `0${num1}` : `${num1}`
    const nextNum = num1 + 1

    // 预加载下一帧
    await preloadNextFrame(nextNum)

    // 更新当前图片
    currentImage.value = nextImage.value
    nextImage.value = ''

    if (num1 >= total) {
      if (animationTimer) {
        clearInterval(animationTimer)
        animationTimer = null
      }
      isPlayingAnimation.value = false
      currentImage.value = defaultImage
      nextImage.value = ''
    }
  }

  // 预加载第一帧
  await preloadNextFrame(1)
  animationTimer = setInterval(play, timing)
}

const playMusic = (path: string) => {
  const innerAudioContext = uni.createInnerAudioContext()
  innerAudioContext.src = `/static/assets/mp3/${path}`
  innerAudioContext.play()
}

const playCymbal = () => {
  playAnimation('cymbal', 12, 100)
  playMusic('pia.mp3')
}

const playFart = () => {
  playAnimation('fart', 27, 100)
  playMusic('pi.wav')
}

const playStomach = () => {
  playAnimation('stomach', 33, 100)
  playMusic('tomaiyou.mp3')
}

onMounted(() => {
  preloadAllAnimations()
})

onUnmounted(() => {
  if (animationTimer) {
    clearInterval(animationTimer)
    animationTimer = null
  }
})
</script>

<style lang="scss" scoped>
.page-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #000;
}

.bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.image-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  min-height: 300px;
  background: #000;
}

.bg-image {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  object-fit: contain;
  will-change: transform, opacity;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  transform-style: preserve-3d;
  perspective: 1000px;
  pointer-events: none;
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  opacity: 1;
  transition: opacity 0.1s ease;

  &.default-image {
    z-index: 1;
  }

  &.animation-image {
    z-index: 2;
  }

  &.preload-image {
    z-index: 1;
    opacity: 0;
  }
}

.controls-container {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
}

.left-controls,
.right-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
}

.action-btn {
  min-width: 100px;
  padding: 12px 20px;
  background: rgba(255, 149, 0, 0.9);
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 4px 12px rgba(255, 149, 0, 0.2);
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;

  &:active {
    transform: scale(0.96) translateY(2px);
    box-shadow: 0 2px 8px rgba(255, 149, 0, 0.2);
  }

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: 0.5s;
  }

  &:hover::before {
    left: 100%;
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .action-btn {
    background: rgba(255, 149, 0, 0.8);
    box-shadow: 0 4px 12px rgba(255, 149, 0, 0.15);
  }
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .controls-container {
    padding: 10px;
  }

  .left-controls,
  .right-controls {
    padding: 10px;
  }

  .action-btn {
    min-width: 80px;
    padding: 10px 16px;
    font-size: 14px;
  }
}
</style>
